package com.wanwu.channel.common.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.wanwu.channel.common.enums.ExceptionEnum;
import com.wanwu.channel.common.exception.SystemException;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.*;

/**
 * xml util
 *
 * @author xun
 * @version 1.0
 * @date 2018/7/16 下午2:36
 * @project channel
 */
public class XmlUtil {

    private static Logger logger = LoggerFactory.getLogger(XmlUtil.class);

    private static final ObjectMapper xmlMapper = new XmlMapper();

    /**
     * bean转成xml报文
     * @param obj
     * @return
     */
    public static String toXml(Object obj) {
        try {
            //xmlMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            return xmlMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            LogUtil.error(logger, e, "序列化bean对象异常");
            throw new RuntimeException(e);
        }
    }

    /**
     * bean转成xml报文(忽略掉为空的属性)
     * @param obj
     * @return
     */
    public static String toXmlNonNull(Object obj) {
        try {
            xmlMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            return xmlMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            LogUtil.error(logger, e, "序列化bean对象异常");
            throw new RuntimeException(e);
        }
    }

    /**
     * xml转bean
     * @param content
     * @param valueType
     * @param <T>
     * @return
     */
    public static <T> T toBean(String content, Class<T> valueType) {
        try {
            return xmlMapper.readValue(content, valueType);
        } catch (IOException e) {
            LogUtil.error(logger, e, "xml转bean异常");
            throw new SystemException(ExceptionEnum.E10036);
        }
    }


    /**
     * 解析xml,返回第一级元素键值对。如果第一级元素有子节点，则此节点的值是子节点的xml数据。
     *
     * @param strxml
     * @return
     * @throws JDOMException
     * @throws IOException
     */
    public static Map doXMLParse(String strxml) throws JDOMException, IOException {
        strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");

        if (null == strxml || "".equals(strxml)) {
            return null;
        }

        Map m = new HashMap();

        InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(in);
        Element root = doc.getRootElement();
        List list = root.getChildren();
        Iterator it = list.iterator();
        while (it.hasNext()) {
            Element e = (Element) it.next();
            String k = e.getName();
            String v = "";
            List children = e.getChildren();
            if (children.isEmpty()) {
                v = e.getTextNormalize();
            } else {
                v = XmlUtil.getChildrenText(children);
            }

            m.put(k, v);
        }

        // 关闭流
        in.close();

        return m;
    }

    /**
     * 获取子结点的xml
     *
     * @param children
     * @return String
     */
    public static String getChildrenText(List children) {
        StringBuffer sb = new StringBuffer();
        if (!children.isEmpty()) {
            Iterator it = children.iterator();
            while (it.hasNext()) {
                Element e = (Element) it.next();
                String name = e.getName();
                String value = e.getTextNormalize();
                List list = e.getChildren();
                sb.append("<" + name + ">");
                if (!list.isEmpty()) {
                    sb.append(XmlUtil.getChildrenText(list));
                }
                sb.append(value);
                sb.append("</" + name + ">");
            }
        }

        return sb.toString();
    }

    public static Map doAlipayQueryXMLParse(String strxml){
        strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");

        if (null == strxml || "".equals(strxml)) {
            return null;
        }

        Map m = new HashMap();
        try {
            InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
            SAXBuilder builder = new SAXBuilder();
            Document doc = builder.build(in);
            Element root = doc.getRootElement();
            List list = root.getChildren();
            Iterator it = list.iterator();
            while (it.hasNext()) {
                Element e = (Element) it.next();
                String k = e.getName();
                Object v = "";
                List children = e.getChildren();
                if (children.isEmpty()) {
                    v = e.getTextNormalize();
                } else {
                    v = XmlUtil.getAlipayQueryChildrenText(children);
                }

                m.put(k, v);
            }

            // 关闭流
            in.close();

        }catch (Exception e){
            throw new RuntimeException(e);
        }
        return m;
    }

    public static Map doAlipayQueryClearanceXMLParse(String strxml) throws JDOMException, IOException {
        strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");

        if (null == strxml || "".equals(strxml)) {
            return null;
        }

        Map m = new HashMap();

        InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(in);
        Element root = doc.getRootElement();
        List list = root.getChildren();
        Iterator it = list.iterator();
        while (it.hasNext()) {
            Element e = (Element) it.next();
            String k = e.getName();
            Object v = "";
            List children = e.getChildren();
            if (children.isEmpty()) {
                v = e.getTextNormalize();
            } else {
                v = XmlUtil.getAlipayQueryClearanceChildrenText(children);
            }

            m.put(k, v);
        }

        // 关闭流
        in.close();

        return m;
    }

    public static Map<String, Object> getAlipayQueryChildrenText(List children) {
        Map<String, Object> childMap = new HashMap<>();
        if (!children.isEmpty()) {
            Iterator it = children.iterator();
            while (it.hasNext()) {
                Element e = (Element) it.next();
                String name = e.getName();
                List attributes = e.getAttributes();
                Iterator iterator = attributes.iterator();
                if (iterator.hasNext()) {
                    Attribute attr = (Attribute) iterator.next();
                    name = attr.getValue();
                }
                Object value = e.getTextNormalize();
                List list = e.getChildren();
                if (!list.isEmpty()) {
                    value = XmlUtil.getAlipayQueryChildrenText(list);
                }
                childMap.put(name, value);
            }
        }
        return childMap;
    }

    public static Map<String, Object> getAlipayQueryClearanceChildrenText(List children) {
        Map<String, Object> childMap = new HashMap<>();
        if (!children.isEmpty()) {
            Iterator it = children.iterator();
            while (it.hasNext()) {
                Element e = (Element) it.next();
                String name = e.getName();
                List attributes = e.getAttributes();
                Iterator iterator = attributes.iterator();
                if (iterator.hasNext()) {
                    Attribute attr = (Attribute) iterator.next();
                    name = attr.getValue();
                }
                Object value = e.getTextNormalize();
                List list = e.getChildren();
                if (!list.isEmpty()) {
                    value = XmlUtil.getAlipayQueryClearanceChildrenText(list);
                    List<Object> values = null;
                    if (null == childMap.get(name)) {
                        values = new ArrayList<>();
                        values.add(value);
                    } else {
                        values = (ArrayList<Object>) childMap.get(name);
                        values.add(value);
                    }
                    childMap.put(name, values);
                } else {
                    childMap.put(name, value);
                }
            }
        }
        return childMap;
    }
}
